﻿using CommonNet48.SerializerUtils;
using DBOptionPro.Model;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DBOptionPro.BLL
{
    /// <summary>
    /// 系统设置信息业务逻辑处理对象
    /// </summary>
    public class SysOptionBLL
    {
        /// <summary>
        /// 系统设置本地保存文件路径
        /// </summary>
        private readonly string _File = Path.Combine(AppContext.BaseDirectory, "Config", "Option.json");

        /// <summary>
        /// 系统设置信息对象
        /// </summary>
        private static SysOption _Option;

        /// <summary>
        /// 获取系统设置信息
        /// </summary>
        /// <returns></returns>
        public SysOption GetOption()
        {
            if (_Option == null)
            {
                _Option = JsonHelper.JsonFileToObject<SysOption>(_File);
                if (_Option == null) _Option = new SysOption();
            }
            return _Option;
        }

        /// <summary>
        /// 保存系统设置信息
        /// </summary>
        public void SaveOption()
        {
            if (_Option == null) return;
            JsonHelper.ObjectToJsonFile(_Option, _File);
        }

        /// <summary>
        /// 测试mysql连接
        /// </summary>
        /// <returns></returns>
        public bool TestLink()
        {
            try
            {
                using (MySqlConnection connection = GetConnection())
                {
                    connection.Open();
                    connection.Close();
                }
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }

        }

        /// <summary>
        /// 获取数据库连接对象(mysql)
        /// </summary>
        /// <returns></returns>
        private MySqlConnection GetConnection()
        {
            if (_Option == null) return null;
            string conStr = $"Database={_Option.DBName};Data Source={_Option.IP};User Id={_Option.User};Password={_Option.Pwd};CharSet=utf8;port={_Option.Port}";
            return new MySqlConnection(conStr);
        }
    }
}
